package com.facexue.miniprogram.api;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.facexue.miniprogram.wechat.handler.MessageHandler;
import com.facexue.miniprogram.wechat.handler.TextMessageHandler;
import com.facexue.miniprogram.wechat.model.Message;
import com.facexue.miniprogram.wechat.utils.MessageUtils;

import jakarta.servlet.http.HttpServletRequest;
import lombok.RequiredArgsConstructor;

@RestController
@RequestMapping("/wechatmp")
@RequiredArgsConstructor
public class WechatApi {
	@Autowired
	private final TextMessageHandler messageHandler;
	
	@Value("${wechat.mp.token}")
	private String token;

	public String handlerMessage(@RequestParam("signature") String signature,
			@RequestParam("timestamp") String timestamp,
			@RequestParam("nonce") String nonce,
			@RequestParam("echostr") String echostr,
			@RequestParam("openid") String openid,
			@RequestParam(value = "encrypt_type", required = false) String encryptType,
			@RequestParam(value = "msg_signature", required = false) String msgSignature,
			HttpServletRequest request) {
		if(!MessageUtils.checkSignature(signature,timestamp,nonce,token)) {
			return "error";
		}
		Message message = MessageUtils.parseMessage(request);
		String response = messageHandler.handler(message);
		return null;
	}
	
}
